from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models.entity import BloodSugar  # 导入上面定义的实体类

# 数据库连接字符串，根据实际情况修改（这里以 MySQL 为例，换成你自己的数据库配置 ）
DATABASE_URI = 'mysql+pymysql://your_username:your_password@localhost:3306/your_database'
engine = create_engine(DATABASE_URI)

# 创建会话工厂，用于创建数据库会话
Session = sessionmaker(bind=engine)

def get_session():
    """获取数据库会话"""
    return Session()

def add_blood_sugar_data(session, time, amount, calorie):
    """添加一条血糖数据到数据库"""
    new_data = BloodSugar(time=time, amount=amount, calorie=calorie)
    session.add(new_data)
    session.commit()
    return new_data.id  # 返回新增数据的 id

def get_all_blood_sugar_data(session):
    """获取所有血糖数据"""
    return session.query(BloodSugar).all()

def update_blood_sugar_data(session, data_id, new_amount=None, new_calorie=None):
    """更新血糖数据"""
    data = session.query(BloodSugar).filter(BloodSugar.id == data_id).first()
    if data:
        if new_amount is not None:
            data.amount = new_amount
        if new_calorie is not None:
            data.calorie = new_calorie
        session.commit()
        return True
    return False

def delete_blood_sugar_data(session, data_id):
    """删除血糖数据"""
    data = session.query(BloodSugar).filter(BloodSugar.id == data_id).first()
    if data:
        session.delete(data)
        session.commit()
        return True
    return False